/*
 * Copyright 2007 Yegor Jbanov
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.spicesoft.clientobjects.samples.form;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.beans.PropertyAdapter;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.spicesoft.clientobjects.BeanEnhancer;

public class AddressPanel extends JPanel {

  private static final long serialVersionUID = 1L;

  private Address address;

  private String title;

  private int rows = 0;

  private CellConstraints cc = new CellConstraints();

  public AddressPanel(Address address, String title) {
    if (address != null) {
      this.address = address;
    } else {
      address = new Address();
      this.address = BeanEnhancer.addPropertyChangeSupport(address);
    }
    this.title = title;

    initUI();
  }

  private void initUI() {
    FormLayout layout = new FormLayout("5dlu, p, 5dlu, p:g, 5dlu",
        "3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu");
    this.setLayout(layout);
    this.setBorder(BorderFactory.createTitledBorder(this.title));

    addTextField(Address.ADDRESS_LINE_1, "Address Line 1");
    addTextField(Address.ADDRESS_LINE_2, "Address Line 2");
    addTextField(Address.CITY, "City");
    addTextField(Address.PROVINCE, "Province");
    addTextField(Address.COUNTRY, "Country");
    addTextField(Address.POSTAL_CODE, "Zip/Postal Code");
  }

  private void addTextField(String fieldName, String labelText) {
    PropertyAdapter adapter = new PropertyAdapter(address, fieldName, true);
    JTextField field = BasicComponentFactory.createTextField(adapter, true);
    rows++;
    this.add(new JLabel(labelText), cc.xy(2, 2 * rows));
    this.add(field, cc.xy(4, 2 * rows));
  }

}
